/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;

import java.util.*;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		Set<String> processedBeans = new HashSet<>();

		/** 判断beanFactory 是不是BeanDefinitionRegistry 如果是则直接调用invokeBeanFactoryPostProcessors,
		 * 否则将 beanDefinitionRegistry转化为BeanFactoryPostProcessor 然后在执行如果是则直接调用invokeBeanFactoryPostProcessors
		 * beanFactory是DefaultListableBeanFactory，是BeanDefinitionRegistry的实现类，所以肯定满足if条件
		 */
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			/**
			 * regularPostProcessors用来存放BeanFactoryPostProcessor
			 */
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			/**
			 * registryProcessors用来存放BeanDefinitionRegistryProcessors
			 * BeanDefinitionRegistryProcessors扩展了BeanFactoryPostProcessor
			 */
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			/**
			 * 循环进来的beanFactoryPostProcessors,正常情况下，beanFactoryPostProcessors肯定是没有数据的
			 * 因为beanFactoryPostProcessors是获得手动添加的，而不是spring扫描的，
			 * 只有手动调用annotationConfigApplicationContext.addBeanFactoryPostProcessor(...)才会有数据
			 */
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				/**
				 * 判断postProcessor是不是BeanDefinitionRegistryPostProcessor,因为BeanDefinitionRegistryPostProcessor
				 * 扩展了BeanFactoryPostProcessor，所以这里首先判断是不是BeanDefinitionRegistryPostProcessor
				 * 如果是的话，直接就执行postProcessBeanDefinitionRegistry(...)方法，然后把对象装到registryProcessors中
				 */
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					/** 注册bean定义后置处理器 这里会解析@Configuration、@Component注解 */
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					/**
					 * 如果不是就装到regularPostProcessors中
					 */
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			/** 这里不会初始化FactoryBeans，会让bean工厂后置处理器去初始化这些常规bean
			 * 并且将这些bean分离出来按照 BeanDefinitionRegistryPostProcessors实现的接口*/
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			/**
			 * 1、调用 实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors后置处理器
			 * 获得实现BeanDefinitionRegistryPostProcessors接口类的BeanName： org.springframework.context.annotation.internalConfigurationAnnotationProcessor
			 * 并且装入数组postProcessorNames中，如果自定义了实现了BeanDefinitionRegistryPostProcessor接口的类，并且也在自定义的类上打上了@Component注解
			 * 在这一步还是拿不到自定义的这个类，因为spring还没有进行扫描。
			 * 扫描是在ConfigurationPostProcessor类中完成的也就是下面的invokeBeanDefinitionRegistryPostProcessors(...)方法
			 */
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					/**
					 * 获得ConfigurationClassPostProcessor并且放到currentRegistryProcessors
					 * ConfigurationClassPostProcessor是很重要的一个类，他实现了BeanDefinitionRegistryPostProcessor接口
					 * BeanDefinitionRegistryPostProcessor又实现了BeanFactoryPostProcessor接口
					 * ConfigurationClassPostProcessor里面执行了扫描Bean，Import，ImportResource等各种操作
					 * 用来处理配置类的各种逻辑
					 */
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					/**
					 * 把name放到processedBeans,后续会根据这个集合来判断处理器是否已经被执行过了
					 */
					processedBeans.add(ppName);
				}
			}
			/**
			 * 排序处理
			 */
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			/**
			 * 合并currentRegistryProcessors，这里为什么要这么做呢？因为registryProcessors是装载BeanDefinitionRegistryPostProcessor的
			 * 一开始的时候，spring只会执行BeanDefinitionRegistryPostProcessor独有的方法，而不会执行BeanDefinitionRegistryPostProcessor
			 * 父类的方法，即BeanFactoryProcessor的方法，所以这里把处理器统一放在集合中，后期统一执行父类方法
			 */
			registryProcessors.addAll(currentRegistryProcessors);
			/**
			 * 第一次调用bean定义后置处理器,这个方法比较重要，需要我们点进去详细研究一下
			 * 可以理解为执行ConfigurationClassPostProcessor的postProcessorBeanDefinitionRegistry()方法
			 * spring热插拔的体现，向ConfigurationClassPostProcessor就相当于一个组件，spring很多的事情就是交给
			 * 组件去管理的，如果不想用这个组件，直接吧注册组件的那一步去掉就可以
			 * 注册@Import等注解也是在这个方法中调用
			 */
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			/**
			 * 因为currentRegistryProcessors是一个临时变量，所以需要清除掉
			 */
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			/**
			 * 2、调用实现Ordered接口的BeanDefinitionRegistryPostProcessors后置处理器
			 * 再次根据BeanDefinitionRegistryPostProcessor获取BeanName，看这个BeanName是否已经被执行过了，有没有实现Ordered接口
			 * 如果没有执行过，也实现了Ordered接口的话，把对象推送到currentRegistryProcessors，名称推送到processedBeans
			 * 如果没有实现Order接口的话，这里不把数据加到currentRegistryProcessors、processedBeans中，后续再做处理
			 * 这里才可以获取我们自定义的实现了BeanDefinitionRegistryPostProcessor的Bean
			 */
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			/**
			 * 排序处理
			 */
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			/**
			 * 合并processors
			 */
			registryProcessors.addAll(currentRegistryProcessors);
			/**
			 * 执行我们自定义的BeanDefinitionRegistryPostProcessor
			 */
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			/**
			 * 清空临时变量
			 */
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			/**
			 * 3、调用其他所有的BeanDefinitionRegistryPostProcessors后置处理器
			 * 上面的代码是执行了实现了Ordered接口的BeanDefinitionRegistryPostProcessor，
			 * 下面的代码是执行没有实现Ordered接口的BeanDefinitionRegistryPostProcessor
			 */
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				/** 第三次调用bean定义后置处理器 */
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			/**
			 * 调用目前处理的所有后置处理器的回调函数
			 * registryProcessors装的是BeanDefinitionRegistryPostProcessor
			 * 上面的代码是执行子类独有的方法，这里需要再把父类的方法也执行一次
			 */
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			/**
			 * regularPostProcessors装的是BeanFactoryPostProcessor，执行BeanFactoryPostProcessor的方法
			 * 但是regularPostProcessors一般情况下，是不会有数据的，只有在外面手动添加BeanFactoryPostProcessor，才会有数据
			 */
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			/** 调用在上下文实例中注册的工厂处理器。 */
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		/** 这里不进行初始化FactoryBeans，而是让bean工厂后置处理器去初始化这些常规的bean */
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,Ordered, and the rest.
		/** 分离出 orderedPostProcessorNames 和nonOrderedPostProcessorNames */
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		/**
		 * 循环BeanNames
		 */
		for (String ppName : postProcessorNames) {
			/**
			 * 如果这个bean被执行过了，则跳过不执行
			 */
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			/**
			 * 如果bean实现了PriorityOrdered接口，则加入到priorityOrderedPostProcessors
			 */
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			/**
			 * 如果bean实现了Ordered接口，则加入到orderedPostProcessorNames
			 */
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			/**
			 * 既没有实现PriorityOrdered接口，也没有实现Ordered接口，则加入到nonOrderedPostProcessorNames
			 */
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		/**
		 * 1、调用实现PriorityOrdered接口的bean工厂后置处理器
		 * 排序处理priorityOrderedPostProcessors,即实现了PriorityOrdered接口的BeanFactoryPostProcessor
		 */
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		/**
		 * 执行priorityOrderedPostProcessor
		 */
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		/**
		 * 2、调用实现Ordered接口实现的bean后置处理器
		 * 执行实现了Ordered接口的BeanFactoryPostProcessor
		 */
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		/**
		 * 3、调用其他所有的bean后置处理器
		 * 执行既没有实现PriorityOrdered接口也没有实现Ordered接口的BeanFactoryPostProcessor
		 */
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		/** 这里会调用EventListenerMethodProcessor.postProcessBeanFactory(),注册事件监听器后置处理器 */
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

	/**
	 * 注册BeanPostProcessors
	 * @param beanFactory
	 * @param applicationContext
	 */
	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		/** 注册一个BeanPostProcessorChecker 当bean在BeanPostProcessor被实例化创建时期间，
		 * 即当有一个bean不符合所有BeanPostProcessors处理的条件时，会记录消息日志*/
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		/** 将实现PriorityOrdered接口，Ordered接口和其他接口的BeanPostProcessors分离开来 */
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		/** 首先，注册实现了PriorityOrdered接口的BeanProcessors */
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		/** 接下来，注册实现Ordered接口的BeanPostProcessors */
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		/** 注册剩余其他的BeanPostProcessors */
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		/** 最后，再注册所有的内部BeanPostProcessors */
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		/** 重新注册后处理器以将内部 bean 注册为 ApplicationListeners，将其移动到处理器链的末尾（用于获取代理等） */
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 * 调用给定的BeanDefinitionRegistryPostProcessor
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			/** 这里调用ConfigutationClassPostProcessor处理beanDefinitionMap中的bean定义 */
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
		/** 遍历postProcessors */
		for (BeanPostProcessor postProcessor : postProcessors) {
			/** 将postProcessor添加到BeanFactory的beanPostProcessors缓存中 */
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
